package newview;

import java.util.Stack;

/**
 * () = 1
 * (x) = 2*x
 * x y = x + y
 * @author TANGYE
 * @date 2021/7/25 5:04 下午
 **/
public class StringMatchCalc {
    public static void main(String[] args) {
        String str = "(12)(1)23";
        System.out.println(judge(str));
    }

    private static int backMatch(Stack<String> stack) {
        /**
         * 倒匹配状态
         * 0 - 初始状态
         * 1 - 已匹配括号
         * 2 - 已匹配括号+数字
         */
        int oneStatus = 1;
        int num = 0;
        while (true) {
            String newStr = stack.pop();
            if (!"(".equals(newStr)) {
                num = add(num, newStr);
                oneStatus = 2;
            } else {
                if (oneStatus == 1) {
                    num += 1;
                } else {
                    num = num*2;
                }
                break;
            }
        }
        return num;
    }

    public static int judge(String str) {
        char[] chars = str.toCharArray();
        Stack<String> stack = new Stack<>();
        int result = 0;
        /**
         * 0 - 正常状态
         * < 0 - 待匹配状态, 待几次匹配
         */
        int status = 0;

        for (char aChar : chars) {
            if ('(' == aChar) {
                status -= 1;
                stack.push(String.valueOf(aChar));
            } else if (')' == aChar) {
                if (0 == status) {
                    return -1;
                }
                status += 1;
                stack.push(String.valueOf(backMatch(stack)));
            } else {
                stack.push(String.valueOf(aChar));
            }
        }

        for (String s : stack) {
            result = add(result, s);
        }
        return result;
    }

    private static int add(int num1, String num2) {
        try {
            return num1 + Integer.valueOf(num2);
        } catch (Exception e) {
            throw new RuntimeException("-1");
        }
    }
}
